{% extends "base.html" %}
{% load static %}
{% load widget_tweaks %}

{% block title %}{% if form.instance.pk %}编辑 MQTT 订阅{% else %}添加 MQTT 订阅{% endif %}{% endblock %}

{% block content %}
<div class="container">
    <div class="row">
        <div class="col-md-10 offset-md-1">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h4 class="mb-0">
                        {% if form.instance.pk %}
                            <i class="bi bi-pencil-square"></i> 编辑 MQTT 订阅
                        {% else %}
                            <i class="bi bi-plus-circle"></i> 添加 MQTT 订阅
                        {% endif %}
                    </h4>
                    {% if form.instance.pk %}
                    <span class="badge {% if form.instance.is_active %}bg-success{% else %}bg-danger{% endif %}">
                        {% if form.instance.is_active %}已启用{% else %}已禁用{% endif %}
                    </span>
                    {% endif %}
                </div>
                <div class="card-body">
                    <form method="post" class="needs-validation" novalidate>
                        {% csrf_token %}
                        
                        {# 基本信息 #}
                        <div class="card mb-4">
                            <div class="card-header">
                                <h5 class="mb-0">基本信息</h5>
                            </div>
                            <div class="card-body">
                                {# 数据源选择 #}
                                <div class="mb-3">
                                    <label for="{{ form.data_source.id_for_label }}" class="form-label fw-bold">
                                        {{ form.data_source.label }} <span class="text-danger">*</span>
                                    </label>
                                    {% render_field form.data_source class="form-select" %}
                                    {% if form.data_source.help_text %}
                                    <div class="form-text">{{ form.data_source.help_text }}</div>
                                    {% endif %}
                                    {% if form.data_source.errors %}
                                    <div class="invalid-feedback d-block">
                                        {% for error in form.data_source.errors %}{{ error }}{% endfor %}
                                    </div>
                                    {% endif %}
                                </div>

                                {# MQTT主题 #}
                                <div class="mb-3">
                                    <label for="{{ form.topic.id_for_label }}" class="form-label fw-bold">
                                        {{ form.topic.label }} <span class="text-danger">*</span>
                                    </label>
                                    {% render_field form.topic class="form-control" placeholder="例如：sensors/temperature" %}
                                    {% if form.topic.help_text %}
                                    <div class="form-text">{{ form.topic.help_text }}</div>
                                    {% endif %}
                                    {% if form.topic.errors %}
                                    <div class="invalid-feedback d-block">
                                        {% for error in form.topic.errors %}{{ error }}{% endfor %}
                                    </div>
                                    {% endif %}
                                </div>

                                {# 启用状态 #}
                                <div class="mb-3">
                                    <div class="form-check form-switch">
                                        {% render_field form.is_active class="form-check-input" %}
                                        <label class="form-check-label" for="{{ form.is_active.id_for_label }}">
                                            {{ form.is_active.label }}
                                        </label>
                                    </div>
                                </div>
                            </div>
                        </div>

                        {# 监控项列表 #}
                        <div class="card mb-4">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <h5 class="mb-0">监控项配置</h5>
                                <button type="button" class="btn btn-primary btn-sm" id="add-item-btn">
                                    <i class="bi bi-plus-lg"></i> 添加监控项
                                </button>
                            </div>
                            <div class="card-body">
                                <div id="items-container">
                                    {{ formset.management_form }}
                                    {% for form in formset.forms %}
                                    <div class="item-form mb-4">
                                        <div class="card">
                                            <div class="card-header d-flex justify-content-between align-items-center">
                                                <h6 class="mb-0">监控项 #<span class="item-number">{{ forloop.counter }}</span></h6>
                                                <button type="button" class="btn btn-danger btn-sm remove-item-btn">
                                                    <i class="bi bi-trash"></i>
                                                </button>
                                            </div>
                                            <div class="card-body">
                                                {# 隐藏字段 #}
                                                {% for hidden in form.hidden_fields %}
                                                    {{ hidden }}
                                                {% endfor %}

                                                <div class="row g-3">
                                                    {# 监控项名称 #}
                                                    <div class="col-md-6">
                                                        <label for="{{ form.name.id_for_label }}" class="form-label fw-bold">
                                                            {{ form.name.label }} <span class="text-danger">*</span>
                                                        </label>
                                                        {% render_field form.name class="form-control" placeholder="请输入监控项名称" %}
                                                        {% if form.name.help_text %}
                                                        <div class="form-text">{{ form.name.help_text }}</div>
                                                        {% endif %}
                                                        {% if form.name.errors %}
                                                        <div class="invalid-feedback d-block">
                                                            {% for error in form.name.errors %}{{ error }}{% endfor %}
                                                        </div>
                                                        {% endif %}
                                                    </div>

                                                    {# 数据键名 #}
                                                    <div class="col-md-6">
                                                        <label for="{{ form.values_id.id_for_label }}" class="form-label fw-bold">
                                                            {{ form.values_id.label }} <span class="text-danger">*</span>
                                                        </label>
                                                        {% render_field form.values_id class="form-control" placeholder="例如：模拟器示例.函数.Random3" %}
                                                        {% if form.values_id.help_text %}
                                                        <div class="form-text">{{ form.values_id.help_text }}</div>
                                                        {% endif %}
                                                    </div>

                                                    {# 单位 #}
                                                    <div class="col-md-6">
                                                        <label class="form-label">
                                                            {{ form.unit.label }}
                                                        </label>
                                                        {% render_field form.unit class="form-control" placeholder="例如：℃、%、MPa" %}
                                                    </div>

                                                    {# 报警条件 #}
                                                    <div class="col-md-4">
                                                        <label class="form-label">
                                                            {{ form.condition.label }} <span class="text-danger">*</span>
                                                        </label>
                                                        {% render_field form.condition class="form-select condition-select" %}
                                                    </div>

                                                    {# 阈值 #}
                                                    <div class="col-md-4">
                                                        <label class="form-label">
                                                            {{ form.threshold_value.label }} <span class="text-danger">*</span>
                                                        </label>
                                                        {% render_field form.threshold_value class="form-control" type="number" step="any" %}
                                                    </div>

                                                    {# 最大阈值 #}
                                                    <div class="col-md-4 threshold-max-container" style="display: none;">
                                                        <label class="form-label">
                                                            {{ form.threshold_max.label }} <span class="text-danger">*</span>
                                                        </label>
                                                        {% render_field form.threshold_max class="form-control" type="number" step="any" %}
                                                    </div>

                                                    {# 报警消息 #}
                                                    <div class="col-12">
                                                        <label class="form-label">
                                                            {{ form.alert_message.label }} <span class="text-danger">*</span>
                                                        </label>
                                                        {% render_field form.alert_message class="form-control" rows="2" %}
                                                        {% if form.alert_message.help_text %}
                                                        <div class="form-text">{{ form.alert_message.help_text }}</div>
                                                        {% endif %}
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    {% endfor %}
                                </div>
                            </div>
                        </div>

                        <div class="d-flex justify-content-between align-items-center">
                            <a href="{% url 'mqtt_subscription_list' %}" class="btn btn-secondary">
                                <i class="bi bi-arrow-left"></i> 返回列表
                            </a>
                            <button type="submit" class="btn btn-primary">
                                <i class="bi bi-save"></i> 保存订阅
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

{% block extra_js %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    const itemsContainer = document.getElementById('items-container');
    const addItemBtn = document.getElementById('add-item-btn');
    const totalFormsInput = document.getElementById('id_form-TOTAL_FORMS');
    
    // 克隆空白表单模板
    const emptyForm = document.querySelector('.item-form').cloneNode(true);
    
    // 添加新的监控项
    addItemBtn.addEventListener('click', function() {
        const newForm = emptyForm.cloneNode(true);
        const formCount = document.querySelectorAll('.item-form').length;
        
        // 更新表单索引
        newForm.innerHTML = newForm.innerHTML.replace(/-\d+-/g, `-${formCount}-`);
        newForm.querySelector('.item-number').textContent = formCount + 1;
        
        // 清空表单值
        newForm.querySelectorAll('input[type="text"], input[type="number"], textarea').forEach(input => {
            input.value = '';
        });
        
        // 添加到容器
        itemsContainer.appendChild(newForm);
        totalFormsInput.value = formCount + 1;
        
        // 重新绑定事件
        bindEvents(newForm);
    });
    
    // 绑定删除按钮事件
    function bindEvents(form) {
        const removeBtn = form.querySelector('.remove-item-btn');
        if (removeBtn) {
            removeBtn.addEventListener('click', function() {
                if (document.querySelectorAll('.item-form').length > 1) {
                    form.remove();
                    updateFormNumbers();
                    totalFormsInput.value = document.querySelectorAll('.item-form').length;
                } else {
                    alert('至少需要保留一个监控项！');
                }
            });
        }
        
        // 绑定条件选择事件
        const conditionSelect = form.querySelector('.condition-select');
        const thresholdMaxContainer = form.querySelector('.threshold-max-container');
        
        if (conditionSelect && thresholdMaxContainer) {
            conditionSelect.addEventListener('change', function() {
                thresholdMaxContainer.style.display = 
                    this.value === 'range' ? 'block' : 'none';
            });
            // 初始化显示状态
            thresholdMaxContainer.style.display = 
                conditionSelect.value === 'range' ? 'block' : 'none';
        }
    }
    
    // 更新表单编号
    function updateFormNumbers() {
        document.querySelectorAll('.item-form').forEach((form, index) => {
            form.querySelector('.item-number').textContent = index + 1;
        });
    }
    
    // 为现有表单绑定事件
    document.querySelectorAll('.item-form').forEach(form => bindEvents(form));
    
    // 表单验证
    const forms = document.querySelectorAll('.needs-validation');
    Array.from(forms).forEach(form => {
        form.addEventListener('submit', event => {
            if (!form.checkValidity()) {
                event.preventDefault();
                event.stopPropagation();
            }
            form.classList.add('was-validated');
        }, false);
    });
});
</script>
{% endblock %}
{% endblock %} 